package com.xigege.config;

import com.spring.annotation.Component;
import com.spring.extend.BeanPostProcessor;
import com.xigege.service.UserServiceImpl;

import java.lang.reflect.Proxy;

@Component
public class HXBeanPostProcessor implements BeanPostProcessor {
    @Override
    public Object postProcessorBeforeInitializing(Object bean, String beanName) {
        System.out.println("初始化前");
        if (beanName.equals("userService")) {
            ((UserServiceImpl) bean).setBeanName("testSetName");
        }
        return bean;
    }

    /**
     * 可以在初始化bean之后生成代理对象执行AOP的逻辑
     *
     * @param bean
     * @param beanName
     * @return
     */
    @Override
    public Object postProcessorAfterInitializing(Object bean, String beanName) {
        System.out.println("初始化后");
        //AOP
        if (beanName.equals("userService")) {
            Proxy.newProxyInstance(bean.getClass().getClassLoader(), bean.getClass().getInterfaces(), (proxy, method, args) -> {
                System.out.println("代理逻辑"); // 找切点
                return method.invoke(bean, args);
            });
        }
        return bean;
    }
}
